package org.zxp.thread.interrupt;

/**
 * @program: zxp-thread-test
 * @description: https://www.cnblogs.com/skywang12345/p/3479949.html
 * @author: X-Pacific zhang
 * @create: 2019-05-07 17:27
 **/
public class InterruptTest {
    /**
     * 注意这里不能在junit @Test里测试，否则调用interrupt后就会中断
     * @param args
     * @throws InterruptedException
     */
    public static void main(String[] args) throws InterruptedException {
        //interrupt并不能中断正在运行的（RUNNABLE）的线程
//        Thread thread = new Thread(() -> {
//            while(true){
//                System.out.println(Thread.currentThread().getState() + " " +Thread.currentThread().isInterrupted());
//            }
//        });
//        thread.start();
//        Thread.sleep(1000);
//        thread.interrupt();

        //interrupt可以通过（程序）判断isInterrupted标志位来决定是否退出线程
//        Thread thread2 = new Thread(() -> {
//            try{newScheduledThreadPool
//                while(!Thread.currentThread().isInterrupted()){
//                    System.out.println(Thread.currentThread().getState());
//                }
//            }finally {
//                System.out.println("我执行了");
//            }
//        });
//        thread2.start();
//        Thread.sleep(1000);
//        thread2.interrupt();

        //interrupt常常被用来终止“阻塞状态”线程，当线程处于阻塞状态时，调用interrupt会抛出InterruptedException异常
        Thread thread3 = new Thread(() -> {
                try {
                    synchronized (InterruptTest.class){
                        InterruptTest.class.wait();
                    }
                } catch (InterruptedException e) {
                    System.out.println("阻塞中的线程才能被中断，并且抛出InterruptedException异常");
                    e.printStackTrace();
                }
        });
        thread3.start();
        Thread.sleep(1000);
        thread3.interrupt();
    }
}
